package edu.ccut.saturn.authority.impl.login;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IMenuInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.component.SaturnMenuManager;

public class FilterMenuInfosByUserAuthority extends DefaultComponent {
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String userType = (String) parameterContext.getParameterValue(0);
		List<SaturnData> userAuthList = (List<SaturnData>) parameterContext
		.getParameterValue(1);

		Collection<IMenuInfo> menuInfos = SaturnMenuManager.getInstance()
				.getAllMenuInfos();
		List<Map<String, String>> menus = new LinkedList<Map<String, String>>();

		if (menuInfos != null) {
			menus.addAll(this.getMenuInfosByMap(userType, userAuthList));
		}
		parameterContext.setParameter(2, menus);

	}

	public List<Map<String, String>> getMenuInfosByMap(String userType, List<SaturnData> userAuthList) {
		List<Map<String, String>> menus = new LinkedList<Map<String, String>>();
		menus = SaturnMenuManager.getInstance().getMenuInfosByMap();
		if (!userType.equals("00")) {
			 filterMenuInfosMayByUserAuthority(userAuthList, menus);
		}
		return menus;
	}
	
	public void filterMenuInfosMayByUserAuthority(List<SaturnData> userAuthList,
			List<Map<String, String>> allNodesList) {
		
			List<Map<String, String>> leafNodeList = new ArrayList<Map<String, String>>();
	
				if (userAuthList != null) {

					for (Map<String, String> nodeInfo : allNodesList) {
						for (SaturnData userAuth : userAuthList) {
							String url = userAuth.getString("url");
							String path = nodeInfo.get("path");
							if (SaturnMenuManager.getInstance().isResourceMapping(url, path)) {
								leafNodeList.add(nodeInfo);
							}
						}
					}
				}
			
			List<Map<String, String>> allContainNodeList = new ArrayList<Map<String, String>>();
			List<Map<String, String>> allDelNodeList = new ArrayList<Map<String, String>>();
			SaturnMenuManager.getInstance().getAllContainNodeList(leafNodeList, allContainNodeList,
					allNodesList);
			for (Map<String, String> nodeMapOfAll : allNodesList) {
				String id = nodeMapOfAll.get("id");
				int isContain = 0;
				for (Map<String, String> nodeMap : allContainNodeList) {
					if (nodeMap.get("id").equals(id)) {
						isContain = 1;
						break;
					}
				}
				if (isContain == 0) {
					allDelNodeList.add(nodeMapOfAll);
				}
			}
			for (Map<String, String> delNodeMap : allDelNodeList) {
				if (allNodesList.contains(delNodeMap)) {
					allNodesList.remove(delNodeMap);
				}
			}
		
	}

}